package com.dxd.onlineshop.mapper;

import com.dxd.onlineshop.pojo.Categories;
import com.dxd.onlineshop.pojo.Product;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface goodsMapper {
    //获取商品的所有分类
    @Select("select id,category_name from categories;")
    List<Categories> getCategories();

    //获取所有商品
    @Select("SELECT id, " +
            "category_id, " +
            "name, " +
            "description, " +
            "price, " +
            "stock_quantity, " +
            "image_url, " +
            "updated_at " +
            "FROM products")
    List<Product> getProducts();

    //减少商品库存
    @Update("update products set stock_quantity=stock_quantity-#{quantity} where id=#{productId}")
    Integer reduceStock(Integer productId, Integer quantity);

    // 添加商品
    @Insert("INSERT INTO products (category_id, name, description, price, stock_quantity, image_url) " +
            "VALUES (#{categoryId}, #{name}, #{description}, #{price}, #{stockQuantity}, #{imageUrl})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int addProduct(Product product);

    // 更新商品信息（包括库存）
    @Update("UPDATE products SET " +
            "category_id = #{categoryId}, " +
            "name = #{name}, " +
            "description = #{description}, " +
            "price = #{price}, " +
            "stock_quantity = #{stockQuantity}, " +
            "image_url = #{imageUrl} " +
            "WHERE id = #{id}")
    int updateProduct(Product product);

    // 根据ID获取单个商品
    @Select("SELECT id, category_id, name, description, price, stock_quantity, image_url, updated_at " +
            "FROM products WHERE id = #{id}")
    Product getProductById(Integer id);

    // 删除商品（可选）
    @Delete("DELETE FROM products WHERE id = #{id}")
    int deleteProduct(Integer id);

    // 根据分类ID获取商品（可选，用于筛选）
    @Select("SELECT id, category_id, name, description, price, stock_quantity, image_url, updated_at " +
            "FROM products WHERE category_id = #{categoryId}")
    List<Product> getProductsByCategoryId(Integer categoryId);

    // 更新商品库存
    @Update("UPDATE products SET stock_quantity = #{newStockQuantity} WHERE id = #{productId}")
    int updateProductStock(Integer productId, Integer newStockQuantity);
}